package com.kedacom.ctsp.authz.oauth2.util;


import com.kedacom.ctsp.authority.entity.User;
import io.jsonwebtoken.*;
import org.joda.time.DateTime;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 我们使用JJWT生成/解析JWT令牌
 */
public class JWTUtil {


    /**
     * 密钥加密token
     *
     * @param priKey
     * @param userName
     * @return
     */
    public static String generateUserToken(byte priKey[], String userName, int expire) throws Exception {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        String compactJws = Jwts.builder()
                .setSubject(userName)
                .claim(User.USERNAME, userName)
                .setIssuedAt(now)
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                .signWith(SignatureAlgorithm.RS256, RsaKeyHelper.getInstance().getPrivateKey(priKey)).compact();


        return compactJws;
    }

    public static String getSubject(String token, byte[] pubKey) throws Exception {
        if (token == null) {
            return null;
        }
        return Jwts.parser().setSigningKey(RsaKeyHelper.getInstance().getPublicKey(pubKey)).parseClaimsJws(token).getBody().getSubject();

    }

    /**
     * 公钥解析token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Jws<Claims> parserClaimsToken(String token, byte[] pubKey) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(RsaKeyHelper.getInstance().getPublicKey(pubKey)).parseClaimsJws(token);
        return claimsJws;
    }


    /**
     * 获取token中的subject用户信息
     *
     * @param token
     * @param pubKey
     * @return
     * @throws Exception
     */
    public static String getInfoFromToken(String token, String pubKey) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, pubKey);
        Claims body = claimsJws.getBody();
        return body.getSubject();
    }

    /**
     * 公钥解析token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Jws<Claims> parserToken(String token, String pubKey) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(pubKey).parseClaimsJws(token);
        return claimsJws;
    }
}
